local skel = fk.CreateSkill {
  name = "emo__yuanding",
  tags = {Skill.Compulsory},
}

skel:addEffect(fk.EventPhaseStart, {
  anim_type = "support",
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(skel.name) and player.phase == Player.Play then
      return table.find(player.room:getOtherPlayers(player), function(p)
        return p:hasSkill(skel.name, true)
      end)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tos = table.filter(room:getOtherPlayers(player), function(p)
      return p:hasSkill(self, true)
    end)
    if #tos == 0 then return false end
    room:doIndicate(player, tos)
    local lowerHp, higherHp = player.hp, player.hp
    for _, p in ipairs(tos) do
      lowerHp = math.min(lowerHp, p.hp)
      higherHp = math.max(higherHp, p.hp)
    end
    table.insert(tos, player)
    local to_recover = table.filter(tos, function (p)return p.hp == lowerHp end)
    local to_draw = table.filter(tos, function (p)return p.hp == higherHp end)
    for _, p in ipairs(to_recover) do
      if p:isWounded() and not p.dead then
        room:recover({ who = p, num = 1, recoverBy = player, skillName = skel.name  })
      end
    end
    for _, p in ipairs(to_draw) do
      if not p.dead then
        p:drawCards(2, skel.name)
      end
    end
  end,
})

skel:addEffect(fk.DamageCaused, {
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(skel.name) then
      return data.to:hasSkill(skel.name) and player ~= data.to
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askToChoice(player, {
      choices = {"emo__yuanding_prevent", "emo__yuanding_loseskill"},
      skill_name = skel.name,
      prompt = "#emo__yuanding_damage:"..data.to.id,
    })
    if choice == "emo__yuanding_prevent" then
      data:preventDamage()
    else
      room:handleAddLoseSkills(player, "-emo__yuanding")
      room:handleAddLoseSkills(data.to, "-emo__yuanding")
    end
  end,
})

skel:addEffect("visibility", {
  card_visible = function (self, player, card)
    local owner = Fk:currentRoom():getCardOwner(card)
    if player:hasSkill(skel.name) and owner and owner:hasSkill(skel.name) then
      return true
    end
  end,
})

Fk:loadTranslationTable{
  ["emo__yuanding"] = "缘定",
  [":emo__yuanding"] = "锁定技，①有“缘定”的其他角色互相可见手牌；<br>"..
  "②出牌阶段开始时，你与“缘定”角色中体力值较小者回复1点体力，体力值较大者摸两张牌，体力值相同则双方均执行两个效果。<br>"..
  "③你对拥有“缘定”的其他角色造成伤害时，须选择防止此伤害，或令你与其失去“缘定”。",

  ["emo__yuanding_prevent"] = "防止对其造成伤害",
  ["emo__yuanding_loseskill"] = "令你与其失去“缘定”",
  ["#emo__yuanding_damage"] = "缘定：防止对 %src 造成伤害，或令你与其失去“缘定”",
}


return skel
